import { useEffect, useState, useRef, forwardRef, useImperativeHandle, useCallback } from 'react';
import { Button, Input, Modal } from 'antd';
import debounce from 'lodash/debounce';
import styles from './index.scss';

const { confirm } = Modal;
/*
  ---- 绘制小窗口
  onSave  保存绘制
  onCancle 取消绘制
*/

export default forwardRef(({ onSave, onCancel, handleDraw }, ref) => {
  const [name, setName] = useState('');

  const showConfirm = name => {
    confirm({
      title: `确定${name}吗?`,
      content: '',
      onOk() {
        name === '保存' ? onSave() : onCancel();
      },
      onCancel() {},
      okText: '确认',
      cancelText: '取消',
      className: styles.modal_wrap,
      cancelButtonProps: {
        type: 'primary',
        ghost: true,
      },
    });
  };

  const handleChange = useCallback(
    debounce(value => {
      setName(value);
    }, 400),
    [],
  );

  useImperativeHandle(ref, () => ({
    name,
  }));

  return (
    <div className={styles.drawBox}>
      <p>
        <Button type="primary" onClick={handleDraw}>
          开启绘制
        </Button>
        &emsp;区划名称
      </p>
      <div className={styles.content}>
        <Input
          placeholder="请输入区划名称"
          size="large"
          allowClear
          onChange={e => handleChange(e.target.value)}
        />
        <div className={styles.btns}>
          <p onClick={() => showConfirm('保存')}>保存</p>
          <p onClick={() => showConfirm('取消')}>取消</p>
        </div>
      </div>
    </div>
  );
});

let mouseTool;
export function useDrawPolygon() {
  const { AMap, map } = window;
  const drawList = useRef(null);

  // 注册绘制事件
  useEffect(() => {
    mouseTool &&
      mouseTool.on('draw', event => {
        drawList.current = event.obj;
        mouseTool && mouseTool.close(false);
        mouseTool = null;
      });
  }, [mouseTool]);

  // 获取区域经纬度列表
  const getPoints = () => {
    const paths = drawList.current.getPath();
    const points = paths.map(({ lng, lat }) => ({ lng, lat }));
    return points;
  };

  // 关闭，并清除覆盖物
  const clearPolygon = () => {
    mouseTool && mouseTool.close(true);
    mouseTool = null;
  };

  // 开启绘制鼠标
  const handleDraw = () => {
    clearPolygon();
    mouseTool = new AMap.MouseTool(map);
    mouseTool.polygon({
      fillColor: '#00b0ff',
      strokeColor: '#80d8ff',
      strokeOpacity: 1,
      strokeWeight: 1.5,
      fillOpacity: 0.05,
      strokeStyle: 'solid',
    });
  };

  return { handleDraw, getPoints, clearPolygon };
}
